package com.hz.framework.dao;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.logicalcobwebs.proxool.ProxoolDataSource;

public class DBQuery {

	private static final long serialVersionUID = 6547617570485599616L;

	public static final Logger logger = LogManager.getLogger(DBQuery.class);

	private Connection conn = null;

	public static DBQuery query = null;

	public static final DataSource ds = (DataSource) new ProxoolDataSource("proxool-pool");

	public QueryRunner qr = null;

	private DBQuery() {
	}

	public static DBQuery getInstance() {
		if (query == null)
			query = new DBQuery();
		return query;
	}

	// -----------------------------------------------------

	// 从连接池获得连接
	public Connection getConnection() {
		closeConnection();
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
		return conn;
	}

	// -----------------------------------------------------------

	// 返回QueryRunner对象
	public QueryRunner getQueryRunner() {
		qr = new QueryRunner(ds); // 这里的QueryRunner不要 传一个连接
		return qr;
	}

	// -----------------------------------------------------------
	// 使用本类必须在需要关闭连接的地方对连接进行关闭
	public void closeConnection() {
		if (conn != null) {
			try {
				conn.close();				
				conn = null;
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
	}
}
